package main.adt.stack;

/**
 * Created by july on 2015/12/21.
 *
 * 栈的链式存储---链栈
 */
public class LinkedStack<E> {

    private int size;       //元素个数
    private Node top;       //栈顶指针

    public LinkedStack(){
        top = null;
    }

    public LinkedStack(E element){
        top = new Node(element,null);
        size++;
    }

    /**
     * 入栈
     * @param element
     */
    public void push(E element){
        top = new Node(element,top);
        size++;
    }

    /**
     * 出栈
     * @return
     */
    public E pop(){
        Node oldNode = top;
        top = top.next;
        oldNode.next = null;
        size--;
        return oldNode.data;
    }

    /**
     * 访问栈顶元素
     * @return
     */
    public E peek(){
        return top.data;
    }

    /**
     * 判断是否为空栈
     * @return
     */
    public boolean isEmpty(){
        return size == 0;
    }

    /**
     * 返回栈的长度
     * @return
     */
    public int size(){
        return size;
    }

    /**
     * 清空栈
     */
    public void clear(){
        top = null;
        size = 0;
    }

    /**
     *  复写toString方法，便于查看集合中的数据
     */
    @Override
    public String toString(){
        if(size == 0){
            return "[]";
        }
        StringBuilder sb = new StringBuilder("[");
        for(Node current = top;current != null;current = current.next){
            if(current.data != null){
                sb.append(current.data.toString()).append(",");
            }else{
                sb.append("Null").append(',');
            }
        }
        int len = sb.length();
        sb.delete(len-1,len).append("]");
        return sb.toString();
    }

    private class Node{
        private E data;      //数据域
        private Node next;   //指针域,指向它的直接后继

        protected Node(E element, Node next) {
            this.data = element;
            this.next = next;
        }
    }
}
